<?php
namespace app\handler\wechat\ai;

use app\facade\Ai;
use app\services\ai\Qq;
use EasyWeChat\Kernel\Contracts\EventHandlerInterface;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\Voice;

class TextMessageHandler implements  EventHandlerInterface
{
    use BaseMessageHandler;

    /**
     * @param $message
     * @return Text
     */
    public function handle($message = null)
    {
        $wechat = $this->getApp();
        $openid = $message['FromUserName'] ?? '';
        $event = $message['MsgType'] ?? '';

        $res = Ai::textChat(['question' => $message['Content'] ?? '']);

        $answer = '';
        if ($res && is_array($res) && ! $res['ret']) {
            $answer = $res['data']['answer'];
        }

        if ($wechat && $answer) {
            $res = Ai::aaiTts([
                'text' => $answer,
            ]);
            if ($res && is_array($res) && ! $res['ret']) {
                //保存到本地
                $filePath = $this->getMediaPath($openid, $event, Qq::$aaiTtsExt[$res['data']['format']]);
                if (file_put_contents($filePath, base64_decode($res['data']['speech']))) {
                    //再调微信接口上传临时素材取media_id
                    $upload = $wechat->media->uploadVoice($filePath);

                    if ($upload && $upload['media_id'] ?? null) {
                        //调用客服消息接口发送图片
                        $result = $wechat->customer_service
                            ->message(new Voice($upload['media_id']))
                            ->to($openid)
                            ->send();

                        if ($result && $result['errcode']) { //失败处理
                            $wechat->customer_service
                                ->message(new Text('手滑了一下，请重试'))
                                ->to($openid)
                                ->send();
                        }
                        return null;
                    }
                }
            }

            $wechat->customer_service
                ->message(new Text('语音合成失败，将以文本形式回复'))
                ->to($openid)
                ->send();

            $wechat->customer_service
                ->message(new Text($answer))
                ->to($openid)
                ->send();
        }

    }
}